package com.vcredit.creditcat.framework.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;

import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;
/**
 *  文件工具
 *
 */
public class FileUtil {
	public static String upload(String inputName, HttpServletRequest request, String directory) throws IOException {
		return upload(inputName, request, directory, null, null);
	}
	
	/**
	 * 上传文件
	 * @param inputName VIEW层表单NAME
	 * @param request HttpServletRequest
	 * @param directory 保存目录
	 * @param sizeLimit 文件大小限制，单位是byte
	 * @param errorMessage 大小超限的错误信息
	 * @return
	 * @throws IOException
	 */
	public static String upload(String inputName, HttpServletRequest request, String directory, Long sizeLimit, String errorMessage) throws IOException {
		MultipartRequest req = (MultipartRequest) request;
		MultipartFile file = req.getFile(inputName);
		 
		if(!file.isEmpty()){
			if (sizeLimit != null && file.getSize() > sizeLimit) throw new IOException(errorMessage);
			Date now = new Date();
			String newDir = getDir(now);
			String realPath = request.getSession().getServletContext().getRealPath(directory)+"/"+newDir; 
			File dir =  new File(realPath);
			if(!dir.exists()){
				dir.mkdir();
			}
			String newFileName = now.getTime()+file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
			file.transferTo(new File(realPath+"/"+newFileName));
			return "/"+directory+"/"+newDir+"/"+newFileName;
		}
		return null;
	}
	/**
	 * 返回上传文件的[]BYTE
	 * @param inputName VIEW层表单NAME
	 * @param request HttpServletRequest
	 * @return
	 * @throws Exception
	 */
	public static byte[] getUploadByte(String inputName,HttpServletRequest request) throws Exception{
		MultipartRequest req = (MultipartRequest) request;
		MultipartFile file = req.getFile(inputName);
		return file.getBytes();
	}
	/**
	 * 格式化日期
	 * @param date
	 * @return
	 */
	private static String getDir(Date date){
		SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
		return format.format(date);
	}
	

	public static String read(Sheet sheet,Workbook workbook,int col, int row){  
		  try{    
		  //获得单元数据  
		    Cell a2 = sheet.getCell(col,row); 
		      String rest = a2.getContents(); 
		     return rest; 
		   }catch(Exception e){ 
		     System.out.println("read err:"+e);   
		   workbook.close();    
		  return null;  
		  } 
		 }
	/**
	 * 读取EXCEL
	 * 
	 * @param sheet
	 * @param workbook
	 * @param col
	 * @param row
	 * @return
	 */
	public static String[] readLine(Sheet sheet,Workbook workbook,int row) {
		try { // 获取数据表列数
			int colnum = sheet.getColumns();
			String[] rest = new String[colnum];
			for (int i = 0; i < colnum; i++) {
				String sTemp = read(sheet,workbook,i, row);
				if (sTemp != null)
					rest[i] = sTemp;
			}
			return rest;
		} catch (Exception e) {
			System.out.println("readLine err:" + e);
			workbook.close();
			return null;
		}
	}
	
	/**
	 * 获得指定目录下面的所有文件名
	 * @param filepath
	 * @param pathMap
	 * @return
	 * @throws Exception
	 */
	public static Map<Integer, String> readfile(String filePath, Map<Integer, String> pathMap) throws Exception {
		  if (pathMap == null) {
		   pathMap = new HashMap<Integer, String>();
		  }
		  File file = new File(filePath); 
		  
		  if (!file.isDirectory()) { 
		   pathMap.put(pathMap.size(), file.getPath());

		  } else if (file.isDirectory()) { 
		   String[] filelist = file.list(); 
		   for (int i = 0; i < filelist.length; i++) { 
		    File readfile = new File(filePath + "/" + filelist[i]); 
		    if (!readfile.isDirectory()) {
		     pathMap.put(pathMap.size(), readfile.getPath());

		    } else if (readfile.isDirectory()) { 
		     readfile(filePath + "/" + filelist[i], pathMap); 
		    } 
		   } 
		  } 
		  return pathMap; 
		 }
	
	private static String getRootPath() {
		return FileUtil.class.getResource("/").getPath() + "../..";
	}
	
	private static String getRealPath(String fileName) {
		return getRootPath() + fileName;
	}
	/**
	 * 根据文件路径在web-root下创建文件夹和文件
	 * @param fileName
	 * @return
	 */
	public static File getRealFile(String filePath) {
		File dir = new File(getRealPath(filePath.substring(0,filePath.lastIndexOf("/"))));
		if(!dir.exists()){
			dir.mkdirs();
		}
		return new File(getRealPath(filePath));
	}
	
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();
		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();

	}
	public static InputStream convertStringToStream(String str){
		try {
			return new ByteArrayInputStream(str.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}  
		return null;
	}
	
}
